package persons.web;

import org.springframework.web.servlet.mvc.SimpleFormController;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.view.RedirectView;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import api.Person;

import server.IAmServer;

/**
 * @author Ann Raboschuk
 */
public class PersonFormController extends SimpleFormController
{
   /** Logger for this class and subclasses */
   protected final Log logger = LogFactory.getLog(getClass());

   private IAmServer server;
   private Long id;
   
   @Override
   public ModelAndView onSubmit(Object command) throws ServletException
   {
      String surname = ((Person) command).getSurname();
      String name = ((Person) command).getName();
      Character sex = ((Person) command).getSex();
      Integer age = ((Person) command).getAge();
      String email = ((Person) command).getEmail();
      String phone = ((Person) command).getPhone();
      String address = ((Person) command).getAddress();
      Person person = new Person(surname, name, age, sex, email, phone, address);
      
      if (id != null)
      {
         person.setId(id);
         logger.info("Updating person: " + person.toString());
         server.edit(person);
      }
      else
      {
         logger.info("Adding person: " + person.toString());
         server.add(person);
      }
      
      logger.info("returning from PersonForm view to "
            + getSuccessView());

      return new ModelAndView(new RedirectView(getSuccessView()));
   }

   protected Object formBackingObject(HttpServletRequest request)
         throws ServletException
   {
      Person person = new Person();
      id = Long.valueOf(request.getParameter("id"));
      if (id != null)
         person = server.getPersonById(id);
      return person;
   }

   public void setServer(IAmServer server)
   {
      this.server = server;
   }

   public IAmServer getServer()
   {
      return server;
   }
}
